"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from django.contrib import admin
from django import forms
from django.utils.translation import gettext_lazy as _
import json

from memorkartoj.models import *
from siriuso.forms.widgets import LingvoInputWidget, LingvoTextWidget
from siriuso.utils.admin_mixins import TekstoMixin


# Форма для модулей
class MemorkartojModuloFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=True)
    priskribo = forms.CharField(widget=LingvoTextWidget(), label=_('Priskribo'), required=True)

    class Meta:
        model = MemorkartojModulo
        fields = [field.name for field in MemorkartojModulo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

# Модули
@admin.register(MemorkartojModulo)
class MemorkartojModuloAdmin(admin.ModelAdmin, TekstoMixin):
    form = MemorkartojModuloFormo
    list_display = ('id', 'nomo_teksto', 'priskribo_teksto')
    exclude = ('id',)

    class Meta:
        model = MemorkartojModulo


# Форма для карточек
class MemorkartojKartoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=True)
    priskribo = forms.CharField(widget=LingvoTextWidget(), label=_('Priskribo'), required=True)

    class Meta:
        model = MemorkartojKarto
        fields = [field.name for field in MemorkartojKarto._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

# Карточки
@admin.register(MemorkartojKarto)
class MemorkartojKartoAdmin(admin.ModelAdmin, TekstoMixin):
    form = MemorkartojKartoFormo
    list_display = ('id', 'nomo_teksto', 'priskribo_teksto')
    exclude = ('id',)

    class Meta:
        model = MemorkartojKarto


# Форма для типов тестов/игр
class MemorkartojTestoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=True)
    priskribo = forms.CharField(widget=LingvoTextWidget(), label=_('Priskribo'), required=True)

    class Meta:
        model = MemorkartojTesto
        fields = [field.name for field in MemorkartojTesto._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

# Типы тестов/игр
@admin.register(MemorkartojTesto)
class MemorkartojTestoAdmin(admin.ModelAdmin, TekstoMixin):
    form = MemorkartojTestoFormo
    list_display = ('id', 'nomo_teksto', 'priskribo_teksto')
    exclude = ('id',)

    class Meta:
        model = MemorkartojTesto


# Форма статистики тестов
class MemorkartojStatistikoFormo(forms.ModelForm):

    class Meta:
        model = MemorkartojStatistiko
        fields = [field.name for field in MemorkartojStatistiko._meta.fields if field.name not in ('krea_dato', 'uuid')]

# Статистика тестов
@admin.register(MemorkartojStatistiko)
class MemorkartojStatistikoAdmin(admin.ModelAdmin, TekstoMixin):
    form = MemorkartojStatistikoFormo
    # list_display = ('id')
    # exclude = ('id',)

    class Meta:
        model = MemorkartojStatistiko


# Форма подписки на чужие модули
class MemorkartojAbonoFormo(forms.ModelForm):

    class Meta:
        model = MemorkartojAbono
        fields = [field.name for field in MemorkartojAbono._meta.fields if field.name not in ('krea_dato', 'uuid')]

# подписка на чужие модули
@admin.register(MemorkartojAbono)
class MemorkartojAbonoAdmin(admin.ModelAdmin, TekstoMixin):
    form = MemorkartojAbonoFormo
    # list_display = ('id')
    # exclude = ('id',)

    class Meta:
        model = MemorkartojAbono

